package com.wits.platform.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.entity.Role;
import com.wits.platform.service.RoleService;
import com.wits.platform.web.mvc.PageParam;


@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{

    @Autowired
    private RoleService roleService;
    
    
    @RequestMapping(value = "/toSelect")
    public String toSelect(){
    	return "platform/role/select";
    }
    
    @RequestMapping(value = "/toList")
    public String toList(){
    	return "platform/role/list";
    }
    
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(Model model,@ModelAttribute("page") PageParam page,HttpServletRequest req) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
		Page<Role> listPage = roleService.findPage(Role.class,searchParams,page);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(),listPage.getContent());
	}
    
    @RequestMapping(value = "/view/{viewType}")
    public String toView(Model model,@PathVariable String viewType,@RequestParam String roleId){
    	if(ViewType.Add.getView().equals(viewType)){
    		model.addAttribute(WebConstants.COMMAND,new Role());
    	}else{
    		model.addAttribute(WebConstants.COMMAND,  roleService.getOne(roleId));
    	}
    	model.addAttribute("viewType",viewType);
    	return "platform/role/roleForm";
    }
    
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(Model model,@ModelAttribute("command") @Valid Role command,@RequestParam String viewType,BindingResult result, HttpServletRequest req) {
        if(result.hasErrors()) {
            model.addAttribute(WebConstants.COMMAND, command);
            return toView(model,viewType,command.getRoleId());
        }
        String resourceIds=req.getParameter("resourceIds");
        String menuIds=req.getParameter("menuIds");
        command.setDateCre(new Date());
        command.setUserCre(getCurrentUserId());
    	roleService.saveCascade(command,menuIds,resourceIds);
        String success=this.getText("add.success");
        return ajaxDoneSuccess(success);
    }
    
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
	@ResponseBody
    public Object update(Model model, @ModelAttribute("command") @Valid Role command,@RequestParam String viewType, BindingResult result,HttpServletRequest req) {
        if(result.hasErrors()) {
            model.addAttribute(WebConstants.COMMAND, command);
            return toView(model,viewType,command.getRoleId());
        }
        String resourceIds=req.getParameter("resourceIds");
        String menuIds=req.getParameter("menuIds");
        command.setDateUpd(new Date());
        command.setUserUpd(getCurrentUserId());
        try{
        	roleService.updateCascade(command,menuIds,resourceIds);
            return ajaxDoneSuccess(this.getText("update.success"));
        }catch(Exception e){
        	return ajaxDoneError(this.getText("update.failed"));
        }
    }
    
    @RequestMapping(value = "/delete")
    @ResponseBody
	public Object delete(@RequestParam String ids) {
		try {
			roleService.deleteInBatch(Arrays.asList(StringUtils.split(ids,",")));
			return ajaxDoneSuccess(this.getText("delete.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("delete.failed"));
		}
	}

    
    @RequestMapping(value = "/changeEnable")
	@ResponseBody
    public Object changeEnable(@RequestParam(value="id") String id,@RequestParam(value="isEnable") String isEnable){
        try {
        	roleService.updateField(Role.class, id,"isEnable",isEnable);
        	return ajaxDoneSuccess(this.getText("update.success"));
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxDoneError(this.getText("update.failed"));
		}
    	
    }
   
}
